#!/bin/bash
USERNAME=$(/usr/bin/id -un)
RAKE_CMD=/usr/bin/rake
BUNDLER_CMD=""

die() {
  echo $*; exit 1
}

cd ~foreman || die "Cannot change to foreman home directory"
[ -f Gemfile ] && [[ -z ${BUNDLER_CMD// } ]] && BUNDLER_CMD="bundle exec"
CMD="$BUNDLER_CMD $RAKE_CMD"
if [ $# -eq 0 ]; then
  $RAKE_CMD -h; exit 0;
elif [ "$USERNAME" = foreman ]; then
  RUBYOPT=-W0 RAILS_ENV=production $CMD "$@"
else
  runuser - foreman -s /bin/bash -c 'RUBYOPT=-W0 RAILS_ENV=production "$0" "$@"' -- $CMD "$@"
fi
